package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.OrderNumberGenerator;
import com.ruoyi.system.domain.dto.XsOrderDto;
import com.ruoyi.system.domain.dto.XsOrderImportDto;
import com.ruoyi.system.domain.vo.XsStatisticsVo;
import com.ruoyi.system.domain.xs.XsOrderEnd;
import com.ruoyi.system.mapper.XsOrderEndMapper;
import com.ruoyi.system.service.IXsOrderEndService;
import com.ruoyi.system.service.IXsOrderSourceService;
import com.ruoyi.system.service.IXsStoreService;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author 97099
 * @description 针对表【xs_order_end(TB 订单 完结表)】的数据库操作Service实现
 * @createDate 2025-01-15 19:12:44
 */
@Service
public class XsOrderEndServiceImpl extends ServiceImpl<XsOrderEndMapper, XsOrderEnd>
        implements IXsOrderEndService {

    @Autowired
    private XsOrderEndMapper orderEndMapper;

    @Autowired
    private IXsOrderSourceService xsOrderSourceService;

    @Autowired
    private IXsStoreService xsStoreService;


    @Override
    public XsStatisticsVo getOrderStatistics(XsOrderDto orderDto) {
        return orderEndMapper.statistics(orderDto);
    }

    @Override
    public void batchImportDataClue(MultipartFile file) {
        ExcelUtil<XsOrderImportDto> util = new ExcelUtil<XsOrderImportDto>(XsOrderImportDto.class);
        if (file.isEmpty()) {
            throw new GlobalException("上传的文件为空");
        }
        int count = 2;

        String orderId = null;
        try (InputStream inputStream = file.getInputStream()) {
            Workbook workbook = new XSSFWorkbook(inputStream); // 支持.xlsx格式的Excel文件

            List<XsOrderEnd> excel = new ArrayList<>();
            // 表存在数据
            List<XsOrderEnd> exist = new ArrayList<>();
            // 表不存在数据
            List<XsOrderEnd> nonentity = new ArrayList<>();
            // 查询全部订单
            List<XsOrderEnd> xsOrderList = this.lambdaQuery().list();

            Map<String, String> map = new HashMap<>();
//            xsOrderSourceService.lambdaQuery().list().forEach(source -> {
//                map.put(source.getSourceName(), source.getSourceCode());
//            });
            xsStoreService.lambdaQuery().list().forEach(store -> {
                map.put(store.getStoreName(), store.getStoreCode());
            });

            // 遍历每个工作表
            for (int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++) {
                Sheet sheet = workbook.getSheetAt(sheetIndex);
                String sheetName = sheet.getSheetName();

//                String result = PinyinUtil.getFirstLetter(sheetName, ""); //获取工作表字符串拼音

                Pattern pat = Pattern.compile("笔|墨");
                Matcher mat = pat.matcher(sheetName);
                String result = mat.find() ? "BM" : "HZG";

                // 数据列表
                List<XsOrderImportDto> importDtoList = util.importExcel(sheetName, file.getInputStream(), 0);

                if (StringUtils.isNotEmpty(importDtoList)) {
                    for (XsOrderImportDto importDto : importDtoList) {
                        orderId = importDto.getAcookieId();
                        XsOrderEnd xsOrder = new XsOrderEnd();
                        // 需要校验客服编号,接单日期,类型是否存在
//                    if (StringUtils.isBlank(importDto.getServiceCode()) ||
//                            StringUtils.isBlank(importDto.getPayTime()) ||
//                            StringUtils.isBlank(importDto.getTitle())) {
//                        throw new GlobalException("第" + count + "条客服编号,接单日期,类型等不能为空");
//                    }
//                        if (StringUtils.isNotEmpty(excel)) {
//                            List<String> orderIdList = excel.stream().map(XsOrder::getAcookieId).filter(Objects::nonNull).collect(Collectors.toList());
//                            if (orderIdList.contains(xsOrder.getAcookieId())) {
//                                throw new GlobalException("第" + count + "条订单编号重复");
//                            }
//                        }
                        BeanUtil.copyProperties(importDto, xsOrder);
                        xsOrder.setWriterNickName(StringUtils.isNotEmpty(importDto.getWriter()) ? importDto.getWriter().trim() : importDto.getWriter());
                        xsOrder.setUpdateBy(SecurityUtils.getUsername());
                        xsOrder.setUpdateTime(DateUtils.getNowDate());
//                        if ( StringUtils.isNotEmpty(map) && StringUtils.isNotEmpty(importDto.getOrderSource()) ) {
//                            xsOrder.setOrderSource(StringUtils.isNotNull(map.get(importDto.getOrderSource())) ?
//                                            map.get(importDto.getOrderSource()).toString() : "9");
//                        }

                        if (StringUtils.isNotEmpty(map)) {
                            Pattern pattern = Pattern.compile("笔|墨");
                            Matcher matcher = pattern.matcher(sheetName);
                            if (matcher.find()) {
                                xsOrder.setStoreCode(map.get("笔墨画千秋"));
                            } else {
                                xsOrder.setStoreCode(map.get("回字格"));
                            }
                        }
                        excel.add(xsOrder);

                        xsOrder.setOrderId(OrderNumberGenerator.generateOrderNumber(result.toUpperCase()));

                        if (StringUtils.isNotEmpty(xsOrder.getStatus())) {
                            xsOrder.setSettlementRemark(xsOrder.getStatus());
                            Pattern pattern = Pattern.compile("已结|代结|结");
                            Matcher matcher = pattern.matcher(xsOrder.getStatus());
                            if (matcher.find()) {
                                xsOrder.setStatus("6");
                            } else {
                                xsOrder.setStatus("4");
                            }
                        } else {
                            xsOrder.setStatus("4");
                        }
                        xsOrder.setCheckSheet(null);

                        if (StringUtils.isNotEmpty(xsOrderList)) {
                            Set<String> orderIdList = xsOrderList.stream().map(XsOrderEnd::getAcookieId)
                                    .filter(id -> id != null && !id.isEmpty())
                                    .collect(Collectors.toSet());

                            if (orderIdList.contains(xsOrder.getAcookieId())) {
                                xsOrderList.stream()
                                        .filter(o -> Objects.equals(o.getAcookieId(), importDto.getAcookieId()))
                                        .findFirst().ifPresent(existingOrder -> {
                                            xsOrder.setId(existingOrder.getId());
                                            xsOrder.setOrderId(existingOrder.getOrderId());
                                            xsOrder.setUpdateBy(SecurityUtils.getUsername());
                                            xsOrder.setUpdateTime(DateUtils.getNowDate());
                                            exist.add(xsOrder);
                                        });
                            } else {
                                xsOrder.setCreateBy(SecurityUtils.getUsername());
                                xsOrder.setCreateTime(DateUtils.getNowDate());
                                nonentity.add(xsOrder);
                            }
                        } else {
                            xsOrder.setCreateBy(SecurityUtils.getUsername());
                            xsOrder.setCreateTime(DateUtils.getNowDate());
                            nonentity.add(xsOrder);
                        }
                        count++;
                    }
                } else {
                    throw new GlobalException("导入失败！excel第" + sheetIndex + 1 + "个工作表内数据为空");
                }
            }

            this.updateOrder(exist);
            if (StringUtils.isNotEmpty(nonentity)) {
                this.saveBatch(nonentity);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new GlobalException("文件读取错误");
        } catch (Exception e) {
            throw new RuntimeException(e + "--" + count + "---" + orderId);
        }
    }

    @Transactional
    public boolean updateOrder(List<XsOrderEnd> updateList) {
        if (StringUtils.isEmpty(updateList)) {
            return true;
        }
        return this.updateBatchById(updateList);
    }
}
